package com.d18_homework.homework1;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) throws DocumentException {
        //获得解析器对象
        SAXReader saxReader = new SAXReader();
        //利用解析器把xml文件加载到内存中，并返回一个文档对象
        Document document = saxReader.read(new File("homework/xml/horses.xml"));
        //获取根标签
        Element rootElement = document.getRootElement();
        //根标签获取student标签
        List<Element> horseElements = rootElement.elements("horse");
        //用来装horse对象的集合
        ArrayList<Horse> list = new ArrayList<>();
        //遍历
        for (Element element : horseElements) {
            //获取id属性
            Attribute attribute = element.attribute("id");
            //获取值
            String id = attribute.getValue();
            //获取name子标签
            Element nameElement = element.element("name");
            //获取name标签的文本值
            String name = nameElement.getText();
            //获取age子标签
            Element ageElement = element.element("age");
            //获取age标签的文本值
            String age = ageElement.getText();
            //创建Horse 对象
            Horse horse = new Horse(id,name,Integer.parseInt(age));
            list.add(horse);
        }
        //遍历horse集合
        for (Horse horse : list) {
            System.out.println(horse);
        }
    }
}
